const jwt = require('jsonwebtoken');
const { query } = require('../config/db');

/**
 * JWT认证中间件
 * 验证请求头中的Authorization token
 */
const authenticateToken = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失'
      });
    }

    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // 查询管理员信息
    const adminUser = await query(
      'SELECT id, username, full_name, role_id, is_active FROM admin_users WHERE id = ? AND is_active = 1',
      [decoded.userId]
    );

    if (adminUser.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户不存在或已被禁用'
      });
    }

    // 将用户信息添加到请求对象
    req.user = {
      id: adminUser[0].id,
      username: adminUser[0].username,
      fullName: adminUser[0].full_name,
      roleId: adminUser[0].role_id
    };

    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        success: false,
        message: '无效的访问令牌'
      });
    }
    
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        success: false,
        message: '访问令牌已过期'
      });
    }

    console.error('认证中间件错误:', error);
    return res.status(500).json({
      success: false,
      message: '认证验证失败'
    });
  }
};

/**
 * 权限验证中间件
 * @param {Array} requiredPermissions - 需要的权限列表
 */
const requirePermissions = (requiredPermissions = []) => {
  return async (req, res, next) => {
    try {
      if (!req.user) {
        return res.status(401).json({
          success: false,
          message: '用户未认证'
        });
      }

      // 查询用户角色权限
      const rolePermissions = await query(
        'SELECT role_name, permissions FROM admin_roles WHERE id = ?',
        [req.user.roleId]
      );

      if (rolePermissions.length === 0) {
        return res.status(403).json({
          success: false,
          message: '用户角色不存在'
        });
      }

      const role = rolePermissions[0];

      // 如果是超级管理员，直接通过
      if (role.role_name === '超级管理员') {
        return next();
      }

      let permissions = [];
      try {
        // MySQL的JSON字段可能直接返回对象/数组，也可能返回字符串
        if (Array.isArray(role.permissions)) {
          // 如果已经是数组，直接使用
          permissions = role.permissions;
        } else if (typeof role.permissions === 'string') {
          // 如果是字符串，尝试解析
          if (role.permissions === '*') {
            permissions = ['*'];
          } else {
            permissions = JSON.parse(role.permissions || '[]');
          }
        } else {
          // 其他情况，设为空数组
          console.warn('未知的权限数据类型:', typeof role.permissions, role.permissions);
          permissions = [];
        }
      } catch (error) {
        console.error('权限解析错误:', error, '原始数据:', role.permissions, '数据类型:', typeof role.permissions);
        permissions = [];
      }

      // 检查是否有超级管理员权限
      if (permissions.includes('*') || permissions.includes('admin:all')) {
        return next();
      }

      // 检查具体权限
      const hasPermission = requiredPermissions.every(permission => 
        permissions.includes(permission)
      );

      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '权限不足',
          required: requiredPermissions,
          current: permissions
        });
      }

      next();
    } catch (error) {
      console.error('权限验证错误:', error);
      return res.status(500).json({
        success: false,
        message: '权限验证失败'
      });
    }
  };
};

/**
 * 可选认证中间件
 * 如果有token则验证，没有token则跳过
 */
const optionalAuth = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      return next();
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const adminUser = await query(
      'SELECT id, username, full_name, role_id FROM admin_users WHERE id = ? AND is_active = 1',
      [decoded.userId]
    );

    if (adminUser.length > 0) {
      req.user = {
        id: adminUser[0].id,
        username: adminUser[0].username,
        fullName: adminUser[0].full_name,
        roleId: adminUser[0].role_id
      };
    }

    next();
  } catch (error) {
    // 可选认证失败时不返回错误，继续执行
    next();
  }
};

/**
 * 小程序用户JWT认证中间件
 * 验证小程序用户的token
 */
const authenticateMiniappToken = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失'
      });
    }

    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // 查询小程序用户信息
    const user = await query(
      'SELECT id, openid, unionid, nickname, avatar_url FROM users WHERE id = ?',
      [decoded.userId]
    );

    if (user.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 将用户信息添加到请求对象
    req.user = {
      userId: user[0].id,
      openid: user[0].openid,
      unionid: user[0].unionid,
      nickname: user[0].nickname,
      avatarUrl: user[0].avatar_url
    };

    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        success: false,
        message: '无效的访问令牌'
      });
    } else if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        success: false,
        message: '访问令牌已过期'
      });
    } else {
      console.error('小程序认证中间件错误:', error);
      return res.status(500).json({
        success: false,
        message: '认证服务异常'
      });
    }
  }
};

module.exports = {
  authenticateToken,
  authenticateMiniappToken,
  requirePermissions,
  optionalAuth
};
